package com.tang.script.command;

import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngineManager;
import java.util.HashMap;
import java.util.Map;

public class DefaultCacheCommandManager implements CacheCommandManager {
    ScriptEngineManager manager = new ScriptEngineManager();
    javax.script.ScriptEngine engine = manager.getEngineByName("groovy");
    private static Map<String, CompiledScript> cache = new HashMap<>();


    public CompiledScript getScript(String key, String scriptText) {
        if (cache.containsKey(key)) {
            return cache.get(key);
        } else {
            try {
                CompiledScript script = ((Compilable) engine).compile(scriptText);
                this.cache.put(key, script);
                return script;
            } catch (RuntimeException | javax.script.ScriptException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
